package me.huha.zhime.service.impl;

import static me.huha.tools.Preconditions.check;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Date;

import me.huha.commons.Result;
import me.huha.ibatis.sqlbuilder.SpecificationBuilder;
import me.huha.spring.Utils;
import me.huha.tools.Invokers;
import me.huha.tools.Invokers.Invoker;
import me.huha.tools.NonceUtils;
import me.huha.zhime.client.AlipayClientService;
import me.huha.zhime.commons.OrderInfoDTO;
import me.huha.zhime.constant.Constant;
import me.huha.zhime.entity.OrderInfoEntity;
import me.huha.zhime.entity.OrderInfoEntity.PaymentStatusEnum;
import me.huha.zhime.entity.OrderInfoEntity_;
import me.huha.zhime.pay.config.AlipayConfig;
import me.huha.zhime.service.OrderService;
import me.huha.zhime.utils.FileOperateUtils;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;

/**
 * @Title: AlipayClientServiceImpl
 * @Author: Yepx
 * @mail: yepx2013@gmail.com
 * @CreateTime: 2017年10月25日 下午4:54:47
 * @Todo: TODO
 */
@Service("alipayClientService")
public class AlipayClientServiceImpl implements AlipayClientService {
	
	@Autowired
	private OrderService orderService;
	
	@Override
	public Result<String> toPay(final OrderInfoDTO dto) {
		
		return Invokers.$(new Invoker<String>() {
			@Override
			public String apply() {
				
				String orderNum = dto.getOrderNum();
				
				OrderInfoEntity entity = OrderInfoEntity.create(OrderInfoEntity.class)
														.findUnique(SpecificationBuilder.builder()
														.where(OrderInfoEntity_.orderNum.eq(orderNum)).build(), null);
				
				if(null != entity){
					Date orderClose = entity.getOrderClose();
					Date date = new Date();
					
					if(date.before(orderClose)){
						orderService.updateOrderPaymentStatus(orderNum, PaymentStatusEnum.unpaid);
					}else{
						orderService.updateOrderPaymentStatus(orderNum, PaymentStatusEnum.orderClose);
						check(true, "该订单已超时");
					}
				}else{
					orderService.createOrUpdateOrderInfo(dto);
				}
				
				// 获得初始化的AlipayClient
				AlipayClient alipayClient = new DefaultAlipayClient(
						AlipayConfig.gatewayUrl, AlipayConfig.app_id,
						AlipayConfig.merchant_private_key, "json",
						AlipayConfig.charset, AlipayConfig.alipay_public_key,
						AlipayConfig.sign_type);

				// 设置请求参数
				AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
				alipayRequest.setReturnUrl(AlipayConfig.return_url);
				alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

				// 商品描述，可空
				String body = "";

				alipayRequest.setBizContent("{\"out_trade_no\":\"" + dto.getOrderNum()
						+ "\"," + "\"total_amount\":\"" + dto.getOrderAmount().toString() + "\","
						+ "\"subject\":\"" + dto.getGoodName() + "\"," + "\"body\":\"" + body
						+ "\"," + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
				
				String result = null;

				// 请求
				try {
					result = alipayClient.pageExecute(alipayRequest).getBody();
				} catch (AlipayApiException e) {
					e.printStackTrace();
				}
				
				String htmlStr = "<!DOCTYPE html>" + 
								 "<html>" + 
								 "<head>" + 
								 "<meta charset=\"UTF-8\">" + 
								 "<title>正在跳转支付页面，请稍等......</title>" +
								 "</head>" + 
								 "<body>" + 
								  result +
								 "</body>" + 
								 "</html>";

				//TODO 创建临时文件
	    		String temp = "temp";
	    		//TODO 判断目录是否存在
	    		Boolean isExis = FileOperateUtils.exisFolder(temp);
	    		if(!isExis)
	    			//TODO 创建文件夹
	    			FileOperateUtils.createFolder(temp);
				
				File file = FileOperateUtils.createFile(temp + "/" + NonceUtils.randomHexLong() + ".html", htmlStr, "UTF-8");
				
	  	        String url = null;
				try {
					 
					 //使用fastdfs 上传
					 FileInputStream inputStream = new FileInputStream(file);
					 FastFileStorageClient storageClient = Utils.Container.getBean(FastFileStorageClient.class);
		  	         StorePath storePath = storageClient.uploadFile(Constant.FASTDFS_GroupName, inputStream, file.length(), FilenameUtils.getExtension(file.getName()));
		  	         url = Constant.FASTDFS_Domain.concat("/").concat(storePath.getFullPath());
		  	         file.deleteOnExit();
					 
		  	         System.out.println(url);
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	  	       
				return url;
			}
		});
	}
}
